<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
  <head>
    <title>编辑采购订单</title>
    <script type="text/javascript">
      Ext.onReady(function(){
        //是否临时保存
        var temporary = new Ext.form.Hidden({
          name: 'temporary',
          value: 0
        });
        
        var purchaseOrderId = new Ext.form.Hidden({
          name: 'id'
        });

        var version = new Ext.form.Hidden({
          name: 'lock_version'
        });
        
        //备注
        var desc = new Ext.form.TextField({
          fieldLabel: '备注',
          name: 'description',
          anchor: '97%'
        });

        //供应商相关combobox
        var vendorTemplate = new Ext.XTemplate('<tpl for="."><div class="search-item">', '{name}', '</div></tpl>');
        var vendorStore = new Ext.data.Store({
          proxy: new Ext.data.HttpProxy({
            url: "/vendor/getAllVendors?for_cbb=true"
          }),
          reader: new Ext.data.JsonReader({
            root: 'root'
          }, [{
              name: 'id'
            }, {
              name: 'name'
            }, {
              name: 'phone'
            }, {
              name: 'linkman'
            }])
        });
        
        //供应商
        var vendor = new Ext.form.ComboBox({
          store: vendorStore,
          fieldLabel: '供应商',
          allowBlank: false,
          blankText: "供应商必须选择",
          valueField: 'id',
          displayField: 'name',
          hiddenName: 'vendor_id',//如果不想提交displayField，则在这儿指定要提交的Key，value就是valueField．
          emptyText: '请选择...',
          //typeAhead: false,
          loadingText: '搜索中...',
          anchor: '95%',
          //pageSize: 10,
          //hideTrigger: false,
          readOnly:false,
          tpl: vendorTemplate,
          minChars: 0,
          itemSelector: 'div.search-item',
          triggerAction: 'all',
          editable:false,
          selectOnFocus:true
        });

        vendor.on('select', function(combo, record, index) {
          linkman.setValue(record.get('linkman'));
          phone.setValue(record.get('phone'));
        });
        

        //要求发货时间
        var actionDate = new Ext.form.DateField({
          fieldLabel: '到货日期',
          allowBlank: false,
          name: 'action_date',
          format: 'Y-m-d', //格式化日期
          //disabledDays: [0,6],	//不让选择周六，周日
          //disabledDaysText: "周末要休息",
          invalidText: "您输入的日期格式不对，正确格式为2010-01-18",
          blankText: "到货日期必须选择",
          emptyText: '到货日期...',
          anchor: '95%'
        });
        
        //合同号
        var contractNumber = new Ext.form.TextField({
          fieldLabel: '合同编号',
          allowBlank: true,
          name: 'contract_number',
          anchor: '95%'
        });

        //联系人
        var linkman = new Ext.form.TextField({
          fieldLabel: '联系人',
          name: 'linkman',
          anchor: '95%',
          allowBlank: false
        });
        
        //联系电话
        var phone = new Ext.form.TextField({
          fieldLabel: '联系电话',
          name: 'phone',
          anchor: '95%',
          allowBlank: false
        });

        //税率
        var taxRate = new Ext.form.NumberField({
          fieldLabel: '税率(%)',
          name:"tax_rate",
          allowBlank: false,
          allowDecimals: true,
          allowNegative: false,
          maxValue: 100,
          anchor: '95%'
        });

        var deliveryAddress = new Ext.form.TextField({
          fieldLabel: '送货地址',
          allowBlank: false,
          name: 'delivery_address',
          anchor: '95%'
        });

        //总金额
        var sumAmount = new Ext.form.NumberField({
          fieldLabel: '总金额',
          name:"amount",
          readOnly:true,
          allowBlank: false,
          allowDecimals: true,
          allowNegative: false,
          anchor: '90%'
        });
        
        //总进项税
        var sumVATAmount = new Ext.form.NumberField({
          fieldLabel: '总税额',
          name:"value_added_tax",
          readOnly:true,
          allowBlank: false,
          allowDecimals: true,
          allowNegative: false,
          anchor: '90%'
        });

        //含税总金额
        var sumTaxAmount = new Ext.form.NumberField({
          fieldLabel: '含税总金额',
          name:"tax_amount",
          readOnly:true,
          allowBlank: false,
          allowDecimals: true,
          allowNegative: false,
          anchor: '90%'
        });
        //--------------------------------------------------------------------------
        //销售订单单号combobox
        var saleOrderNumberTemplate = new Ext.XTemplate('<tpl for="."><div  class="search-item">', '{order_number}', '</div></tpl>');
        var saleOrderNumberStore = new Ext.data.Store({
          proxy: new Ext.data.HttpProxy({
            url: "/sale_order/getSaleOrersForPurchase"
          }),
          reader: new Ext.data.JsonReader({
            totalProperty: 'totalProperty',
            root: 'root'
          }, [{
              name: 'id'
            }, {
              name: 'order_number'
            }])
        });
        //销售订单CBB
        var saleOrderNumberCBB = new Ext.form.ComboBox({
          store: saleOrderNumberStore,
          fieldLabel: '销售订单单号',
          allowBlank: false,
          blankText: "销售订单必须选择",
          emptyText: '请选择...',
          displayField: 'order_number',
          hideTrigger:false,
          triggerAction:"all",
          //typeAhead: false,
          loadingText: '搜索中...',
          anchor: '100%',
          //pageSize: 10,
          //hideTrigger: false,
          tpl: saleOrderNumberTemplate,
          minChars: 0,
          itemSelector: 'div.search-item',
          selectOnFocus:true
        });

        saleOrderNumberCBB.on('select', function(combo, record, index) {
          var purchaseOrderItemRecord = purchaseOrderDetailSM.getSelected();
          if (!purchaseOrderItemRecord) {
            return false;
          }
          purchaseOrderItemRecord.set('sale_order_id',record.get('id'));
          purchaseOrderItemRecord.set('sale_order_number',record.get('order_number'));
          purchaseOrderItemRecord.set('product_name',null );
          purchaseOrderItemRecord.set('product_id',null );
          purchaseOrderItemRecord.set('number',null );
          purchaseOrderItemRecord.set('spec',null );
          purchaseOrderItemRecord.set('unit',null );
          purchaseOrderItemRecord.set('quantity',null );
          purchaseOrderItemRecord.set('description',null );
          purchaseOrderItemRecord.set('is_suit',null );
          purchaseOrderItemRecord.set('unit_price',null );
          purchaseOrderItemRecord.set('amount',null );
        });

        //产品列表
        var productTemplate = new Ext.XTemplate('<tpl for="."><div class="search-item">','<div style="float:left; width:220px">{name}</div><div style="float:left; width:110px">{number}</div>{is_suit}','</div></tpl>');
        
        var productStore = new Ext.data.Store({
          proxy: new Ext.data.HttpProxy({
            url: "/sale_order/getProductsOfSaleOrder"
          }),
          reader: new Ext.data.JsonReader({
            totalProperty: 'totalProperty',
            root: 'root'
          }, [{
              name: 'id'
            },{
              name: 'number'
            }, {
              name: 'product_id',
              mapping:'id'
            }, {
              name: 'name'
            }, {
              name: 'spec'
            }, {
              name: 'unit'
            }, {
              name: 'unit_price'
            }, {
              name: 'quantity'
            }, {
              name: 'description'
            }, {
              name: 'is_suit',
              mapping:'is_suit',
              convert:function(value,record){
                if(value == "1"){
                  return "套装";
                }else if(value == "0"){
                  return "单品";
                }
              }
            }])
        });
        //产品
        var productCBB = new Ext.form.ComboBox({
          store: productStore,
          allowBlank: false,
          blankText: "产品必须选择",
          emptyText: '请选择...',
          displayField: 'name',
          //typeAhead: false,
          loadingText: '搜索中...',
          anchor: '95%',
          pageSize: 10,
          tpl: productTemplate,
          minChars: 0,
          itemSelector: 'div.search-item',
          selectOnFocus:true
        });

        productCBB.on('select', function(combo, record, index) {
          var purchaseOrderItemRecord = purchaseOrderDetailSM.getSelected();
          if (!purchaseOrderItemRecord) {
            return false;
          }
          /*if (isDuplicateBySaleOrderProduct(purchaseOrderDetailDS,purchaseOrderItemRecord.get('sale_order_id'),record.get('product_id'))){
            //择情删除当前记录
            if (purchaseOrderItemRecord.get('product_id') === record.get('product_id')){
              purchaseOrderItemRecord.set('quantity',record.get('quantity'));
            }else{
              purchaseOrderDetailDS.remove(purchaseOrderItemRecord);
            }            
          }else{*/
          purchaseOrderItemRecord.set('number',record.get('number'));
          purchaseOrderItemRecord.set('spec',record.get('spec'));
          purchaseOrderItemRecord.set('unit',record.get('unit'));
          purchaseOrderItemRecord.set('unit_price',record.get('unit_price'));
          purchaseOrderItemRecord.set('amount',record.get('unit_price'));
          purchaseOrderItemRecord.set('quantity',record.get('quantity'));
          purchaseOrderItemRecord.set('product_id',record.get('product_id'));
          //判断套装
          purchaseOrderItemRecord.set('is_suit',record.get('is_suit'));
          //设置sale_order_detail
          //purchaseOrderItemRecord.set('sale_order_detail_id',record.get('id'));
          /*
          Ext.Ajax.request({
            url : '/stock/getProductStockQuantity',
            success : function (result, request) {
              purchaseOrderItemRecord.set('stock_quantity_1',result.responseText.split("|")[0]);
              purchaseOrderItemRecord.set('stock_quantity_2',result.responseText.split("|")[1]);
              if (purchaseOrderItemRecord.get('sale_order_id') != 0){
                //限制即时最大采购数
                Ext.Ajax.request({
                  url : '/purchase_order/getProductQuantityForPurchase',
                  success : function (result, request) {
                    purchaseOrderItemRecord.set('quantity',result.responseText);
                    purchaseOrderItemRecord.set('balance_quantity',result.responseText);
                    getSumAmount();
                    //得到某采购订单已经入库的某产品的数量
                    Ext.Ajax.request({
                      url : '/purchase_order/getEntryProductQuantityForPurchase',
                      success : function (result, request) {
                        purchaseOrderItemRecord.set('ed_quantity',result.responseText);
                      },
                      failure : function (result, request){
                        Ext.MessageBox.show({
                          title: '消息',
                          msg: "通讯失败，请从新操作",
                          buttons: Ext.MessageBox.OK,
                          icon: Ext.MessageBox.WARNING
                        });
                      },
                      method : 'GET',
                      params : {
                        purchase_order_id : purchaseOrderId.getValue(),
                        sale_order_id : purchaseOrderItemRecord.get('sale_order_id'),
                        product_id : record.get('product_id')
                      }
                    });
                  },
                  failure : function (result, request){
                    Ext.MessageBox.show({
                      title: '消息',
                      msg: "通讯失败，请从新操作",
                      buttons: Ext.MessageBox.OK,
                      icon: Ext.MessageBox.WARNING
                    });
                  },
                  method : 'GET',
                  params : {
                    sale_order_id : purchaseOrderItemRecord.get('sale_order_id'),
                    product_id : record.get('product_id')
                  }
                });
              } else{
                purchaseOrderItemRecord.set('balance_quantity',1000000);
              }
            },
            failure : function (result, request){
              Ext.MessageBox.show({
                title: '消息',
                msg: "通讯失败，请从新操作",
                buttons: Ext.MessageBox.OK,
                icon: Ext.MessageBox.WARNING
              });
            },
            method : 'GET',
            params : {
              id : record.get('product_id')
            }
          });
          //}*/
        });

        productCBB.on('focus', function(combo, record, index) {
          var records = purchaseOrderDetailGrid.getSelectionModel().getSelections();
          productStore.baseParams.id = records[0].get('sale_order_id');
          productStore.load();
        });
        
        //采购订单列表Grid Store
        var purchaseOrderDetailDS = new Ext.data.Store({
          proxy: new Ext.data.HttpProxy({
            url: '/purchase_order/getPurchaseOrderDetailsByIdForEdit'
          }),
          reader: new Ext.data.JsonReader({
            totalProperty: 'totalProperty',
            root: 'root'
          }, [{
              name: 'id'
            },{
              name: 'sale_order_id'
            },{
              name: 'sale_order_detail_id'
            },{
              name: 'sale_order_number'
            },{
              name: 'number'
            }, {
              name: 'product_name'
            }, {
              name: 'spec'
            }, {
              name: 'unit'
            }, {
              name: 'description'
            }, {
              name: 'unit_price',
              type: 'float'
            }, {
              name: 'quantity',
              type: 'int'
            }, {
              name: 'tax_price',
              type: 'float'
            }, {
              name: 'tax_amount',
              type: 'float'
            }, {
              name: 'value_added_tax',
              type: 'float'
            },{
              name: 'product_id'
            },{
              name: 'amount',
              type: 'float'
            },{
              name: 'balance_quantity',
              type: 'int'
            },{
              name: 'ed_quantity',
              type: 'int'
            },{
              name: 'stock_quantity_1',
              type: 'int'
            },{
              name: 'stock_quantity_2',
              type: 'int'
            },{
              name: 'is_suit',
              mapping: 'is_suit',
              convert:function(value,record){
                if(value == "1"){
                  return "套装";
                }else if(value == "0"){
                  return "单品";
                }
              }
            }])
        });
        purchaseOrderDetailDS.baseParams.purchase_order_id = <%=params[:id]%>;
        purchaseOrderDetailDS.load();
        //生成产品Grid的CM
        var purchaseOrderDetailSM = new Ext.grid.CheckboxSelectionModel({singleSelect:true});
        //var purchaseOrderDetailSM = new Ext.grid.RowSelectionModel({singleSelect:true});
        var purchaseOrderDetailCM = new Ext.grid.ColumnModel({defaults: {
            sortable: true,
            menuDisabled: false
          },columns:[new Ext.grid.RowNumberer(),purchaseOrderDetailSM,{
              header: 'id',
              dataIndex: 'id',
              hidden:true,
              width: 40
            },{
              header: '销售订单Id',
              dataIndex: 'sale_order_id',
              hidden:true,
              width: 30
            },{
              header: '销售订单详细Id',
              dataIndex: 'sale_order_detail_id',
              hidden:true,
              width: 30
            },{
              header: '销售订单',
              dataIndex: 'sale_order_number',
              editor: saleOrderNumberCBB,
              width: 195
            },{
              header: '产品名称',
              dataIndex: 'product_name',
              editor: productCBB,
              width: 390
            },{
              header: '产品ID',
              dataIndex: 'product_id',
              width: 50,
              hidden: false
            },{
              header: '产品编号',
              dataIndex: 'number',
              width: 95
            },{
              header: '规格',
              dataIndex: 'spec',
              width: 50
            },{
              header: '单位',
              dataIndex: 'unit',
              width: 50
            },{
              header: '数量',
              align: 'right',
              dataIndex: 'quantity',
              editor: new Ext.form.NumberField({
                allowBlank: false,
                allowDecimals: false,
                allowNegative: false
              }),
              align: 'right',
              width: 50
            },{
              header: '工库',
              dataIndex: 'stock_quantity_1',
              align: 'right',
              hidden:true,
              renderer: stockQuantityRender,
              width: 50
            },{
              header: '大库',
              dataIndex: 'stock_quantity_2',
              align: 'right',
              hidden:true,
              renderer: stockQuantityRender,
              width: 50
            },{
              header: '单价',
              dataIndex: 'unit_price',              
              renderer: Ext.util.Format.numberRenderer('0,000.0000000000'),
              align: 'right',
              width: 110
            },{
              header: '金额',
              dataIndex: 'amount',
              renderer: Ext.util.Format.numberRenderer('0,000.00'),
              align: 'right',
              width: 70
            },{
              header: '含税单价',
              dataIndex: 'tax_price',
              editor: new Ext.form.NumberField({
                allowBlank: false,
                allowDecimals: true,
                allowNegative: false,
                decimalPrecision: 2
              }),
              renderer: Ext.util.Format.numberRenderer('0,000.00'),
              align: 'right',
              width: 80
            },{
              header: '进项税',
              dataIndex: 'value_added_tax',
              renderer: Ext.util.Format.numberRenderer('0,000.00'),
              align: 'right',
              width: 70
            },{
              header: '含税金额',
              dataIndex: 'tax_amount',
              renderer: Ext.util.Format.numberRenderer('0,000.00'),
              align: 'right',
              width: 80
            },{
              header: '套装',
              dataIndex: 'is_suit',
              width: 45
            },{
              header: '备注',
              dataIndex: 'description',
              width: 60,
              editor:new Ext.form.TextField({
                name: 'description',
                anchor: '90%'
              })
            },{
              header: '销售采购差',
              dataIndex: 'balance_quantity',
              width: 90,
              hidden: true
            },{
              header: '已入库数',
              dataIndex: 'ed_quantity',
              width: 90,
              hidden: true
            }
          ]});

        //生成要订单的产品的Grid
        var purchaseOrderDetailGrid = new Ext.grid.EditorGridPanel({
          store: purchaseOrderDetailDS,
          cm: purchaseOrderDetailCM,
          sm: purchaseOrderDetailSM,
          width: 1230,
          height: 315,
          //frame: true,
          //title: '进货品种列表',
          //frame: true,
          //plugins: checkColumn,
          clicksToEdit: 1,//这里应该是单击就可以修改的意思。因为默认是要双击的。
          tbar: [{
              text: '添加产品',
              iconCls: 'addItem',
              handler : function(){
                // access the Record constructor through the grid's store
                var Product = purchaseOrderDetailGrid.getStore().recordType;
                var record = new Product({
                  sale_order_id:0,
                  sale_order_number: '无销售订单关联'
                });
                /*var record = new Product({
                  sale_order_number: '请选择销售订单',product_name: '请选择产品'
                });*/
                purchaseOrderDetailGrid.stopEditing();
                purchaseOrderDetailDS.insert(0, record);
                purchaseOrderDetailGrid.startEditing(0, 0);
              }
            },{
              text: '删除',
              iconCls: 'remove',
              handler : function(){
                var record = purchaseOrderDetailSM.getSelected();
                if (!record) {
                  return false;
                }
                getSumAmount();
                purchaseOrderDetailDS.remove(record);
              }
            }]
        });

        //暂时保存按钮
        var submitButton = new Ext.Button({
          text: '提交',
          tooltip: '提交采购订单。',
          iconCls: 'icon-save',
          handler: function(){
            if (vendor.getRawValue() === vendor.getValue()){
              vendor.reset();
            }
            if (purchaseOrderFormPanel.form.isValid()) {              
              var productsJsonStr = gridStoreToJson(purchaseOrderDetailDS,rejectKeyArray);
              if (purchaseOrderDetailDS.getCount() == 0 || productsJsonStr === ""){
                Ext.MessageBox.show({
                  title: '提示',
                  msg: "您还没有选择有效的产品或选择的产品数量为0！",
                  buttons: Ext.MessageBox.OK,
                  icon: Ext.MessageBox.INFO
                });
                return;
              }

              //检查一下，有没有销售，产品，价格三元素完全相同的记录存在。如果存在就要检查
              if (isDuplicateForPurchase(purchaseOrderDetailDS)){
                Ext.MessageBox.show({
                  title: '消息',
                  msg: "有销售，产品，价格三者完全相同的记录存在，请检查！",
                  buttons: Ext.MessageBox.OK,
                  icon: Ext.MessageBox.INFO
                });
                return;
              }
              
              this.disable();
              var allJsonStr = purchaseOrderFormPanel.getForm().getValues();
              allJsonStr = Ext.util.JSON.encode(allJsonStr);
              allJsonStr = Ext.util.Format.substr(allJsonStr,0,allJsonStr.length-1);
              allJsonStr = allJsonStr + ",\"products\":" + productsJsonStr + "}";
              Ext.Ajax.request({
                url : '/purchase_order/update',
                success : function (result, request) {
                  if (Ext.util.JSON.decode(result.responseText).info.indexOf("成功") > -1) {
                    Ext.MessageBox.show({
                      title: '消息',
                      msg: "保存采购订单，操作成功！",
                      buttons: Ext.MessageBox.OK,
                      icon: Ext.MessageBox.INFO
                    });
                  }
                  else {
                    Ext.MessageBox.show({
                      title: '消息',
                      msg: Ext.util.JSON.decode(result.responseText).info,
                      buttons: Ext.MessageBox.OK,
                      icon: Ext.MessageBox.WARNING
                    });
                  }
                  editPurchaseOrderWin.destroy();
                },
                failure : function (result, request){
                  Ext.MessageBox.show({
                    title: '消息',
                    msg: "通讯失败，请从新操作",
                    buttons: Ext.MessageBox.OK,
                    icon: Ext.MessageBox.WARNING
                  });
                  editPurchaseOrderWin.destroy();
                },
                method : 'POST',
                params : {
                  data : Ext.util.JSON.encode(allJsonStr),
                  authenticity_token: authToken.getValue()
                }
              });
            }
          }
        });

        //临时保存按钮
        var tempSaveButton = new Ext.Button({
          text: '暂存',
          tooltip: '暂时保存采购订单。',
          iconCls: 'temp-save',
          handler: function(){
            //首先把临时变量设置为1
            temporary.setValue(1);

            if (purchaseOrderFormPanel.form.isValid()){
              var productsJsonStr = gridStoreToJson(purchaseOrderDetailDS,rejectKeyArray);
              if (purchaseOrderDetailDS.getCount() == 0 || productsJsonStr === ""){
                Ext.MessageBox.show({
                  title: '提示',
                  msg: "您还没有选择有效的产品或选择的产品数量为0！",
                  buttons: Ext.MessageBox.OK,
                  icon: Ext.MessageBox.INFO
                });
                return;
              }

              //检查一下，有没有销售，产品，价格三元素完全相同的记录存在。如果存在就要检查
              if (isDuplicateForPurchase(purchaseOrderDetailDS)){
                Ext.MessageBox.show({
                  title: '消息',
                  msg: "有销售，产品，价格三者完全相同的记录存在，请检查！",
                  buttons: Ext.MessageBox.OK,
                  icon: Ext.MessageBox.INFO
                });
                return;
              }
              
              this.disable();
              var allJsonStr = purchaseOrderFormPanel.getForm().getValues();
              allJsonStr = Ext.util.JSON.encode(allJsonStr);
              allJsonStr = Ext.util.Format.substr(allJsonStr,0,allJsonStr.length-1);
              allJsonStr = allJsonStr + ",\"products\":" + productsJsonStr + "}";

              Ext.Ajax.request({
                url : '/purchase_order/update',
                success : function (result, request) {
                  if (Ext.util.JSON.decode(result.responseText).info.indexOf("成功") > -1) {
                    Ext.MessageBox.show({
                      title: '消息',
                      msg: "暂存采购订单，操作成功！",
                      buttons: Ext.MessageBox.OK,
                      icon: Ext.MessageBox.INFO
                    });
                  }
                  else {
                    Ext.MessageBox.show({
                      title: '消息',
                      msg: Ext.util.JSON.decode(result.responseText).info,
                      buttons: Ext.MessageBox.OK,
                      icon: Ext.MessageBox.WARNING
                    });
                  }
                  editPurchaseOrderWin.destroy();
                },
                failure : function (result, request){
                  Ext.MessageBox.show({
                    title: '消息',
                    msg: "通讯失败，请联系管理员！",
                    buttons: Ext.MessageBox.OK,
                    icon: Ext.MessageBox.WARNING
                  });
                  editPurchaseOrderWin.destroy();
                },
                method : 'POST',
                params : {
                  data : Ext.util.JSON.encode(allJsonStr),
                  authenticity_token: authToken.getValue()
                }
              });
            }
          }
        });
        tempSaveButton.disable();
        //暂时保存按钮
        var closeButton = new Ext.Button({
          text: '关闭',
          tooltip: '关闭当前窗口，并且当前编辑的信息不能保存。',
          iconCls: 'exit',
          handler: function(){
            editPurchaseOrderWin.destroy();
          }
        });
        
        //采购申请的FormPanel
        var purchaseOrderFormPanel = new Ext.form.FormPanel({
          //baseCls: 'x-plain',
          //renderTo: 'edit_purchase_order',
          labelWidth: 65,
          width: 1243,
          labelAlign: 'right',
          frame : true,
          url: '/purchase_order/update',
          method: 'GET',
          reader: new Ext.data.JsonReader({
            root: 'root'
          }, [{
              name: 'id'
            }, {
              name: 'vendor_id'
            }, {
              name: 'amount'
            }, {
              name: 'value_added_tax'
            }, {
              name: 'tax_amount'
            }, {
              name: 'description'
            }, {
              name: 'action_date',
              type: 'date',
              dateFormat: 'Y/m/d'
            }, {
              name: 'contract_number'
            }, {
              name: 'linkman'
            }, {
              name: 'phone'
            }, {
              name: 'tax_rate'
            }, {
              name: 'delivery_address'
            },{
              name: 'lock_version'
            }]),
          //defaultType: 'textfield',
          items: [{
              layout: 'column',
              border: false,
              items: [{
                  columnWidth: .2,
                  layout: 'form',
                  border: false,
                  items: [vendor]
                }, {
                  columnWidth: .25,
                  layout: 'form',
                  border: false,
                  items: [actionDate]
                }, {
                  columnWidth: .2,
                  layout: 'form',
                  border: false,
                  items: [contractNumber]
                }, {
                  columnWidth: .2,
                  layout: 'form',
                  border: false,
                  items: [taxRate]
                }]
            },{
              layout: 'column',
              border: false,
              items: [{
                  columnWidth: .2,
                  layout: 'form',
                  border: false,
                  items: [linkman]
                }, {
                  columnWidth: .25,
                  layout: 'form',
                  border: false,
                  items: [phone]
                },{
                  columnWidth: .55,
                  layout: 'form',
                  border: false,
                  items: [deliveryAddress]
                }]
            },{
              layout: 'column',
              border: false,
              items: [{
                  columnWidth: 1,
                  layout: 'form',
                  border: false,
                  items: [desc]
                }]
            },{
              layout: 'column',
              border: false,
              items: [{
                  columnWidth: 1,
                  layout: 'form',
                  border: false,
                  items: [purchaseOrderDetailGrid]
                }]
            },{
              layout: 'column',
              border: false,
              items: [{
                  columnWidth: 0.25,
                  layout: 'form',
                  border: false,
                  items: [sumAmount]
                },{
                  columnWidth: 0.25,
                  layout: 'form',
                  border: false,
                  items: [sumVATAmount]
                },{
                  columnWidth: 0.25,
                  layout: 'form',
                  border: false,
                  items: [sumTaxAmount]
                }]
            },purchaseOrderId,temporary,version],
          buttons: [submitButton,tempSaveButton,closeButton]
        });

        purchaseOrderFormPanel.form.load({
          url: '/purchase_order/getPurchaseOrderById?id=' + <%=params[:id]%>,
          method : 'GET',
          waitMsg: '正在载入数据...',
          success: function(form, action){
            var respJson = Ext.util.JSON.decode(action.response.responseText);
            vendor.setRawValue(respJson.root[0].vendor.name);
          },
          failure: function(form, action){
            Ext.MessageBox.show({
              title: '消息',
              msg: "信息加载失败！",
              buttons: Ext.MessageBox.OK,
              icon: Ext.MessageBox.WARNING
            });
            editPurchaseOrderWin.destroy();
          }
        });
          
        purchaseOrderFormPanel.render('edit_purchase_order');
        //
        purchaseOrderDetailGrid.on('afteredit', afterEdit, this );

        function afterEdit(obj) {
          
          if(obj.field=="product_name"||obj.field=="quantity"||obj.field=="tax_price"){
            if (obj.record.get('quantity') > obj.record.get('balance_quantity')){
              obj.record.set('quantity',obj.record.get('balance_quantity'));
            }
            if(obj.record.get('quantity')>0){
              //设置含税单价和含税竞价
              obj.record.set('unit_price',Math.round(10000000000*obj.record.get('tax_price')/(1+taxRate.getValue()*0.01))/10000000000);
              obj.record.set('tax_amount',obj.record.get('tax_price')*obj.record.get('quantity'));
              obj.record.set('amount',Math.round(obj.record.get('quantity')*100*obj.record.get('unit_price'))/100);
              obj.record.set('value_added_tax',Math.round(obj.record.get('amount')*taxRate.getValue()*0.01*1000)/1000);
            }else{
              obj.record.set('amount',0);
            }
          }
          getSumAmount();
        }

        function getSumAmount(){
          sumAmount.setValue(0);
          sumVATAmount.setValue(0);
          sumTaxAmount.setValue(0);
          var records = purchaseOrderDetailDS.getRange(0,purchaseOrderDetailDS.getCount());
          for(var i = 0; i< records.length ;i++){
            var record = records[i];
            var quantity = record.get('quantity');
            var unitPrice = record.get('unit_price');
            var taxPrice = record.get('tax_price');
            //record.set('amount',quantity*unitPrice);
            //record.set('tax_amount',quantity*taxPrice);
            //var amount = record.get('amount');
            sumAmount.setValue(sumAmount.getValue()+record.get('amount'));
            sumVATAmount.setValue(sumVATAmount.getValue()+record.get('value_added_tax'));
            sumTaxAmount.setValue(sumTaxAmount.getValue()+record.get('tax_amount'));
          }
        }
      })
    </script>
  </head>
  <body>
    <div id="edit_purchase_order"></div>
  </body>
</html>